package com.ybg.engine.task;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.ybg.util.CSVUtils;
import com.ybg.util.LogUtil;
 /**
 * @author huang nc
 * @since  2017年5月5日
 * 统计每天上课的总数
 */
public class CountEveryDayCourseTask extends Task{

	private static boolean running = false;
	public List<Map<String,Object>> exportData = new ArrayList<Map<String,Object>>();
	public LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>();
    
    @Override
	public void run() throws Exception {
	 if (!enter()){
            throw new RuntimeException("调度已经在进行中");
        }
        LogUtil.warn("teacher-course-stati...begin........");
        long begin = new Date().getTime();

        System.out.println("你看到我了吗？");
        CountEveryDayCourse();
        CreateCSVData();
        long end = new Date().getTime();
        LogUtil.info("本次任务用时 :" + (end - begin) / 1000 + "秒");
        LogUtil.warn("teacher-course-stati...begin........");
        leaving();
	}

	/**
	 * 统计每天课程总数
	 */
	private int CountEveryDayCourse() {
		Map<String,Object> configMap = getCurrentWeek();
		int weekday = getWeekDay();
		String week = configMap.get("week").toString();
		int countCourse = 0;
		String weeksSql = " SELECT count(*) from ( select kcdm from YBG_B_SCHEDULE_TEACHER where xn=? and xq= ? and xqj = ? and (to_number(substr(qsjsz,1,instr(qsjsz,'-',1,1)-1))<= "+week+" and "+week+" <=to_number(substr(qsjsz,instr(qsjsz,'-',1,1)+1,3)) or instr(qsjsz,'"+week+"')<>0)) ";
		countCourse = jdbcTemplate.queryForObject(weeksSql,Integer.class,configMap.get("xn").toString(),configMap.get("xq").toString(),String.valueOf(weekday));
	
		return countCourse;
		//System.out.println(countCourse);
	}
	
	
	/**
     * 获取学期信息
     * @return
     */
    private Map<String,Object> getTermConfig(){
    	List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();
    	String sqlString = "select paramkey,PARAMVALUE from SYSTEM_CONFIG ";
    	listMap = jdbcTemplate.queryForList(sqlString);
    	
    	String term = null;
        String termTime = null;
        String firstDayOfWeek = null;
    	for (Map<String, Object> map : listMap) {
    		if (map.get("PARAMKEY").equals("schedule_currentTermToShow")) {
    			term = (String) map.get("PARAMVALUE");
			}
			if (map.get("PARAMKEY").equals("schedule_currentTermDateToShow")) {
				termTime = (String) map.get("PARAMVALUE");
			}
			if (map.get("PARAMKEY").equals("firstDayOfWeek")) {
				firstDayOfWeek = (String) map.get("PARAMVALUE");
			}
		}
    	
        Map<String,Object> map = new HashMap<>();
        if (term != null && termTime != null) {
            try{
                String[] termStr = term.split(",");
                String[] termTimeStr = termTime.split(",");
                map.put("xn",termStr[0]);
                map.put("xq",termStr[1]);
                map.put("kssj",termTimeStr[0]);
                map.put("jssj",termTimeStr[1]);
                map.put("firstDayOfWeek",firstDayOfWeek); 
            }catch (Exception e){
                return null;
            }
        }
        return map;
    }
	/**
     * 获取当前周
     * @return
     */
    private Map<String,Object> getCurrentWeek(){
        Map<String,Object> termConfig = getTermConfig();
        if (termConfig==null)return null;
        Calendar beginDayCal = Calendar.getInstance();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            beginDayCal.setTime(sf.parse(termConfig.get("kssj").toString()));
        }catch (ParseException e) {
            e.printStackTrace();
        }
        //把开始时间设置为周的第一天,便于计算周数
        if (termConfig.get("firstDayOfWeek").equals("7")){
            beginDayCal.set(Calendar.DAY_OF_WEEK,Calendar.SUNDAY);
        }else {
            beginDayCal.set(Calendar.DAY_OF_WEEK,Integer.valueOf(termConfig.get("firstDayOfWeek").toString())+1);
        }

        long begin = beginDayCal.getTimeInMillis();
        long now = System.currentTimeMillis();

        int zs = (int)((now - begin)/(1000*60*60*24*7))+1;
        termConfig.put("week",String.valueOf(zs));
        return termConfig;
    }
    /**
     * 获取星期几
     * @return
     */
    private int getWeekDay(){
        Calendar calendar = Calendar.getInstance();
        int weekday = calendar.get(Calendar.DAY_OF_WEEK);
        weekday = weekday==1?7:weekday-1;
        return weekday;
    }

    private void CreateCSVData() {
    	int count = CountEveryDayCourse();
    	Map<String, Object> map2 = new HashMap<String, Object>();
    	map2.put("CountCourse", count);
		exportData.add(map2);
		
		map.put("1", "CountCourse");
		map.put("2", "mark"); 
	    
	    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");  
	    String str = simpleDateFormat.format(new Date());

	    //String path = "d:/export/";
	   String path = "/opt/ybg/jobengine/csvfile/";
		String fileName = "CountCourse"+str+".csv";  
	    File file = CSVUtils.createCSVFile(exportData, map, path, fileName);  
	}
    
    
	private synchronized boolean enter(){
        if(running){
            return false;
        }else{
            running = true;
            return true;
        }
    }

    private synchronized void leaving(){
        running = false;
    }

	@Override
	public String setSuccessResultMsg() {

		return "统计每天课程总数成功";
	}

	
	
}
